package com.jshcbd.modules.asset.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jshcbd.framework.poi.excel.ExcelImportUtil;
import com.jshcbd.framework.poi.excel.entity.ImportParams;
import com.jshcbd.framework.query.QueryGenerator;
import com.jshcbd.modules.asset.entity.AssetClassesEntity;
import com.jshcbd.modules.asset.entity.CompanyEntity;
import com.jshcbd.modules.asset.service.IClassesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.jshcbd.framework.vo.Result;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhoucd
 * @date
 * @description
 */
@Slf4j
@Api(tags="资产分类")
@RestController
@RequestMapping("/classes")
public class AssetClassesontroller {
    @Autowired
    private IClassesService classesService;


    @ApiOperation("资产分类")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<AssetClassesEntity>> queryPageList(AssetClassesEntity assetClassesEntity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<AssetClassesEntity>> result = new Result();
        QueryWrapper<AssetClassesEntity> queryWrapper = QueryGenerator.initQueryWrapper(assetClassesEntity, req.getParameterMap());
        queryWrapper.orderByAsc("code");
        Page<AssetClassesEntity> page = new Page(pageNo, pageSize);
        IPage<AssetClassesEntity> pageList = classesService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setData(pageList);
        log.info(pageList.toString());
        return result;
    }


    @ApiOperation("获取资产分类信息")
    @GetMapping( "/getInfo/{id}")
    public Result<AssetClassesEntity> queryPageList(@PathVariable String id,HttpServletRequest req) {
        Result<AssetClassesEntity> result = new Result();
        AssetClassesEntity entity =   classesService.getById(id);
        result.setData(entity);
        return result;
    }

    @ApiOperation("新增资产分类")
    @PostMapping("/add")
    public Result add(@RequestBody AssetClassesEntity assetClassesEntity) {
        try {
            classesService.save(assetClassesEntity);
            return Result.ok("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }


    @ApiOperation("修改分类信息")
    @PutMapping("/edit")
    public Result edit(@RequestBody AssetClassesEntity assetClassesEntity) {
        try {
            AssetClassesEntity entity = classesService.getById(assetClassesEntity.getId());
            if(entity==null) {
                return Result.error("未找到对应实体");
            }else {
                classesService.updateById(assetClassesEntity);
                return Result.ok("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    @ApiOperation("删除分类")
    @DeleteMapping("/delete")
    public Result delete(@RequestParam String id) {
        try {
            this.classesService.removeById(id);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * excel导入
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    public Result importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            try {
                List<AssetClassesEntity> list = ExcelImportUtil.importExcel(file.getInputStream(), AssetClassesEntity.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                classesService.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return Result.ok();
    }



}



